/*
 * Copyright (C), 2005-2019, 深圳市珍爱网信息技术有限公司
 */

package org.idea.ietty.container;

import org.idea.ietty.container.bean.TestController;
import org.idea.ietty.container.bean.User;
import org.idea.ietty.container.bean.UserService;

import java.io.InputStream;
import java.util.List;

/**
 * @author linhao
 * @date 2020/5/7
 * @Version V1.0
 */
public class ClassPathXmlApplicationContext implements IettyApplicationContext {

    private BeanFactory beanFactory;

    private BeanConfigParser beanConfigParser;

    public ClassPathXmlApplicationContext(String location) {
        this.beanFactory = new BeanFactory();
        this.beanConfigParser = new XmlBeanConfigParser();
        this.loadBeanDefainitions(location);
    }


    private void loadBeanDefainitions(String configLocation) {
        InputStream in = null;
        in = this.getClass().getClassLoader().getResourceAsStream(configLocation);
        if (in == null) {
            throw new RuntimeException("can not find config file "+configLocation);
        }
        List beanDefinitions = beanConfigParser.parse(in);
        beanFactory.addBeanDefinitions(beanDefinitions);
    }

    @Override
    public Object getBean(String beanId) {
        return beanFactory.getBean(beanId);
    }

    public static void main(String[] args) {
        IettyApplicationContext iettyApplicationContext = new ClassPathXmlApplicationContext("config/ietty.xml");
        TestController testController = (TestController) iettyApplicationContext.getBean("testController");
        System.out.println("===========");
        testController.doTest1();
    }
}
